const { execSQL } = require('../db/mysql');
const { md5 } = require('../extend/utils');

// 更新userAgent
const setAgantFun = (username, password, agent) => {
	const setAgantSql = `UPDATE app_user SET agent = '${agent}' WHERE username='${username}' AND password='${password}';`;
	execSQL(setAgantSql);
}

// 用户登录授权检查
const appLoginCheck = (userAgent) => {
	const selectSql = `SELECT * from app_user WHERE agent='${userAgent}' LIMIT 1;`;
	return execSQL(selectSql);
}

// 获取用户详情
const getAppUserFun = (type, whereData) => {
	let selectSql;
	switch (type) {
		case 'phone':
			selectSql = `SELECT * from app_user WHERE phone='${whereData}' LIMIT 1;`;
			return execSQL(selectSql);
		default:
			selectSql = `SELECT * from app_user WHERE id='${whereData}' LIMIT 1;`;
			return execSQL(selectSql);
	}
}

// 用户登录
const loginFun = (username, password) => {
	const agent = md5(`${username}${new Date().getTime()}`);
	const selectSql = `SELECT * from app_user WHERE username='${username}' AND password='${password}';`;
	return execSQL(selectSql).then(loginResult => {
		setAgantFun(username, password, agent);
		return {
			...loginResult[0],
			agent
		};
	});
}

// 用户注册
const siginUpFun = (data) => {
	const sql = `insert into app_user (role_id, phone, username, password, status) values ('1', '${data.phone}', '${data.userName}', '${md5(data.password)}', '1');`;
	return execSQL(sql);
}


module.exports = { 
	appLoginCheck,
	getAppUserFun,
	loginFun,
	siginUpFun
}
